package cn.net.yugu.doraemon.common.dal.repository;

import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * 支持遍历
 *
 * @param <ID> 表主键
 * @param <Q>  查询类类型
 * @param <T>  实体类类型
 * @author xiangzr
 * @version 2023/4/1 10:31:07
 */
public interface TraverseRepository<T, ID, Q> extends Repository<T, ID> {

    /**
     * 获取遍历表的迭代器
     *
     * @param query
     * @return
     */
    Iterator<List<T>> traverse(Q query);

    /**
     * 获取遍历表的 <code>Stream<T> </code>
     *
     * @param query
     * @return
     */
    default Stream<T> traverseStream(Q query) {
        final Iterator<List<T>> listIterator = traverse(query);
        final Spliterator<List<T>> listSpliterator = Spliterators.spliteratorUnknownSize(listIterator, Spliterator.ORDERED);
        final Stream<T> tStream = StreamSupport.stream(listSpliterator, false)
                .flatMap(ts -> ts.stream());
        return tStream;
    }
}
